package com.ics.atable.chat.controller;

import com.ics.atable.chat.model.dto.CustomChatResponse;
import com.ics.atable.chat.service.LlmService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;


/**
 * llm 接口
 *
 * @author haohongbin
 */
@Tag(name = "llm API接口", description = "llm API接口")
@RestController
@RequestMapping("/llm")
public class LlmController {

    private final LlmService llmService;

    public LlmController(LlmService llmService) {
        this.llmService = llmService;
    }

    @Operation(summary = "llm接口")
    @GetMapping("/call")
    public String call(@RequestParam(value = "用户提示词", required = true) String userPrompt,
                       @RequestParam(value = "会话ID", required = true) String sessionId) {
        return llmService.call(userPrompt, sessionId);
    }

    @Operation(summary = "llm接口，流式返回")
    @GetMapping(value = "/stream/call")
    public Flux<CustomChatResponse> streamCall(HttpServletResponse response,
                                               @RequestParam(value = "用户提示词", required = true) String userPrompt) {
        // 避免返回乱码
        response.setCharacterEncoding("UTF-8");
        Flux <ChatResponse> chatResponses = llmService.streamCall(userPrompt);
        return chatResponses.map(resp -> {
            CustomChatResponse customChatResponse = new CustomChatResponse();
            customChatResponse.setContent(resp.getResult().getOutput().getText());
            return customChatResponse;
        });
    }
}
